"""
    User's Delicious account handler
    
    Enables setting a user's Delicious account details
    
    @author: Jean-Lou Dupont
    
    ?username=XYZ&password=ABC
"""

import os
import sys
import logging
import string

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db

from libs.wiki import template

from libs.user.prefs import UserPrefs

class DeliciousHandler(webapp.RequestHandler):
    
    def get(self):
        user = users.get_current_user()
        
        if user:
            userPrefs = UserPrefs.create(user)
        
            try:
                username = userPrefs.delicious_username
                password = userPrefs.delicious_password
                self.response.set_status( 200 )
            except:
                username = ''
                password = ''
                self.response.set_status( 400 )
            
            self.response.headers["Content-Type"] = "application/json"
            self.response.out.write("{ \"username\": \"%s\", \"password\": \"%s\" }" % (username, password))
        else:
            self.response.set_status( 401 )
    
    def post(self):
        user = users.get_current_user()
        
        if user:
            userPrefs = UserPrefs.create(user)
            username = self.request.get("username")
            password = self.request.get("password")
            logging.info("DeliciousHandler.post: username[%s] password[%s]" % (username, password))
            try:
                userPrefs.delicious_username = db.Text( username )
                userPrefs.delicious_password = db.Text( password )
                userPrefs.put()    
                self.response.set_status( 200 )
                self.response.out.write("{ 'code': '200' }")
            except Exception, e:
                self.response.out.write( e.message )
                self.response.set_status( 400 )
        else:
            self.response.set_status( 401 )

#========================================================================================================

def main():
    application = webapp.WSGIApplication([('/user/delicious/', DeliciousHandler) ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()        